package com.chuangke.common.utils;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.CharEncoding;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;

public class ZipUtils {

	public static final String XLS = ".xls";
	public static final String XLSX = ".xlsx";
	public static final String ZIP = ".zip";

	public static void downloadExcelZip(HttpServletResponse response, String zipName, Map<String, Workbook> workBooks)
			throws IOException {
		response.setCharacterEncoding(CharEncoding.UTF_8);
		response.setContentType("multipart/form-data");
		response.addHeader("Content-Disposition",
				"attachment;filename=" + URLEncoder.encode(getFullName(zipName, ZIP), CharEncoding.UTF_8));

		ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
		for (String workbookName : workBooks.keySet()) {
			out.putNextEntry(new ZipEntry(getFullExcelName(workbookName, workBooks.get(workbookName))));
			workBooks.get(workbookName).write(out);
			out.closeEntry();
		}
		out.close();
	}

	public static void downloadFileZip(HttpServletResponse response, String zipName, Map<String, byte[]> files)
			throws IOException {
		response.reset();
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition",
				"attachment;fileName=\"" + URLEncoder.encode(getFullName(zipName, ZIP), CharEncoding.UTF_8) + "\"");
		// 设置压缩流：直接写入response，实现边压缩边下载
		// 循环将文件写入压缩流DataOutputStream
		try (ZipOutputStream zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
				DataOutputStream os = new DataOutputStream(zipos)) {
			zipos.setMethod(ZipOutputStream.DEFLATED); // 设置压缩方法

			for (String file : files.keySet()) {
				// 添加ZipEntry，并ZipEntry中写入文件流
				zipos.putNextEntry(new ZipEntry(file));
				os.write(files.get(file));
				zipos.closeEntry();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String getFullName(String fileName, String suffix) {
		if (!fileName.endsWith(suffix)) {
			fileName += suffix;
		}
		return fileName;
	}

	private static String getFullExcelName(String fileName, Workbook workbook) {
		String suffix = XLSX;
		if (workbook instanceof HSSFWorkbook) {
			if (fileName.endsWith(suffix)) {
				fileName = fileName.substring(0, fileName.length() - 1);
			}
			suffix = XLS;
		}
		if (!fileName.endsWith(suffix)) {
			fileName += suffix;
		}
		return fileName;
	}
}
